<template>
  <div class="el-month-select">
    <el-date-picker
      :value="dateStart"
      type="month"
      :editable="false"
      :clearable="false"
      value-format="yyyy-MM"
      :size="dateSize"
      @input="changeStart"
      :style="{ width: dateWidth }"
      placeholder="选择月">
    </el-date-picker>
    <span class="monToMon" :style="{ width: spanWidth }">至</span>
    <el-date-picker
      :value="dateEnd"
      type="month"
      :editable="false"
      :clearable="false"
      value-format="yyyy-MM"
      :size="dateSize"
      @input="changeEnd"
      :style="{ width: dateWidth }"
      placeholder="选择月">
    </el-date-picker>
  </div>
</template>

<script>
  export default {
    name: "el-month-select",
    props:{
      dateStart:{
        type: String,
        required: true
      },
      dateEnd:{
        type: String,
        required: true
      },
      dateChange: {
        type: Function,
        required: true
      },
      dateSize:{
        type: String,
        default: 'small'
      },
      dateWidth: {
        type: String,
        default: '140px'
      },
      spanWidth:{
        type: String,
        default: '40px'
      },
      limitSet: {
        type: Boolean,
        default: false
      },
      limitNum: {
        type: Number,
        default: 12
      }
    },
    data() {
      return {
      }
    },
    mounted() {
    },
    methods: {
      changeStart (val){
        if(this.dateEnd){
          let dateEnd = new Date(this.dateEnd)
          if(new Date(val) > dateEnd){
            this.$message.error("开始时间不能大于结束时间")
            return
          }
          if(this.limitSet && new Date(val) < new Date(dateEnd.getFullYear(),(dateEnd.getMonth() - this.limitNum))){
            this.$message.error(`最大时间间隔为${this.limitNum}个月`)
            return
          }
          this.dateChange({ dateStart: val, dateEnd: this.dateEnd })
        }
        this.$emit('update:dateStart', val)
      },
      changeEnd (val){
        if(this.dateStart){
          let dateStart = new Date(this.dateStart)
          if(new Date(val) < dateStart){
            this.$message.error("结束时间不能小于开始时间")
            return
          }
          if(this.limitSet && new Date(val) > new Date(dateStart.getFullYear(),(dateStart.getMonth() + this.limitNum))){
            this.$message.error(`最大时间间隔为${this.limitNum}个月`)
            return
          }
          this.dateChange({ dateStart: this.dateStart, dateEnd: val })
        }
        this.$emit('update:dateEnd', val)
      }
    }
  }
</script>

<style scoped>
  .el-month-select{
    display: flex;
  }
  .monToMon{
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
